package ReSofting.it.GoldDirector;


import java.util.ArrayList;

import java.util.UUID;

import org.apache.http.HttpEntity;

import ReSofting.it.GoldDirector.R.drawable;
import ReSofting.it.GoldDirector.Adapters.ItemOrdineAdapter;
import ReSofting.it.GoldDirector.Adapters.MenuAdapter;
import ReSofting.it.GoldDirector.Helpers.InputBox;
import ReSofting.it.GoldDirector.Helpers.InputBoxBool;
import ReSofting.it.GoldDirector.Helpers.InputBoxNewOrder;
import ReSofting.it.GoldDirector.Helpers.ItemsLoader;
import ReSofting.it.GoldDirector.Helpers.SaveOrderAsync;
import ReSofting.it.GoldDirector.Helpers.resVarie;
import ReSofting.it.GoldDirector.Interfaces.IInputBoxBool;
import ReSofting.it.GoldDirector.Interfaces.IInputBoxDelegate;

import ReSofting.it.GoldDirector.Interfaces.IRemoteSaveCall;
import ReSofting.it.GoldDirector.Model.GlobalDatas;
import ReSofting.it.GoldDirector.Model.InputData;
import ReSofting.it.GoldDirector.Model.myAggiunta;
import ReSofting.it.GoldDirector.Model.myMenu;
import ReSofting.it.GoldDirector.Model.myOrdine;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

public class OrderItemsActivity extends TabActivity  
 implements 
  IInputBoxDelegate<InputData>, IRemoteSaveCall<HttpEntity>,
  IInputBoxBool
{
  
	ProgressDialog _progrDialog = null;
	private ListView _ItemsOrdineList ;
	
	private static OrderItemsActivity _me ;
	
	TextView _infoOrdineTxt = null;
	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.orderitems);
                  
        _me = this;
     
        makeTabHostInit();       
        Log.d("In OrderItemsActivity onCreate","Start");
                        
         
		 if(checkItemsInCache())
	     {        
	     	Log.d("In OrderItemsActivity onCreate","Check : true");
	     }
        
        makeTabHost();
        setButtonsHandlers() ;
        
        datiTempAggiunte();            
        
        _infoOrdineTxt = (TextView) findViewById(R.id.textOrder_InfoOrdine);

	}//fM
	
	 protected void onSaveInstanceState(Bundle outState) {
       
         outState.putString("INFOORDINE", (String)_infoOrdineTxt.getText());         
         super.onSaveInstanceState(outState);
        }
        
        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState) {
         
         _infoOrdineTxt.setText(savedInstanceState.getString("INFOORDINE")) ;         
         GlobalDatas.OrderAdapter.notifyDataSetChanged();	 
              	
         super.onRestoreInstanceState(savedInstanceState);
        }
        
	
	 private void datiTempAggiunte() {
		
		 GlobalDatas.AggiunteList.clear();
		 GlobalDatas.AggiunteList.add(new myAggiunta( 0, "Pizze","Origano"  ));
		 GlobalDatas.AggiunteList.add(new myAggiunta( 0,"Pizze","Basilico"  ));
		 GlobalDatas.AggiunteList.add(new myAggiunta( 0,"Pizze","Speck"  ));
		 GlobalDatas.AggiunteList.add(new myAggiunta( 0,"Pizze","Salamino"  ));
		 GlobalDatas.AggiunteList.add(new myAggiunta( 0,"Pizze","Prosciutto"  ));
	}

	//Menues*********************************************************
	   @Override 
	   public boolean onCreateOptionsMenu(Menu menu) {	
	   	return resVarie.onCreateOptionsMenu(menu, this);
	   }//fM


	   @Override
	   public boolean onOptionsItemSelected(MenuItem item) {	
	   	return resVarie.handlerMenu(item, this);	 
	   } //fm
	
	
	private Boolean checkItemsInCache()
	{
		
		ItemsLoader itL = new ItemsLoader(this);
    	
    	itL.caricaCategorieInCacheFromDb();
    	itL.caricaMenuItemsInCacheFromDb();
    	
    	itL.CloseDb();
    	itL = null;
		
		
		if(GlobalDatas.CategorieList == null) 
		{
			resVarie.showMessageDialog( "Caricare Items Menu please", this);
			return false;
	
		}
		
		if(GlobalDatas.MenuList == null) 
			{
			resVarie.showMessageDialog( "Caricare Items Menu please", this);
				return false;		
			}
		
		if((GlobalDatas.CategorieList.size() ==0) | (GlobalDatas.MenuList.size() == 0 ) ) 
		{
			resVarie.showMessageDialog( "Caricare Items Menu please", this);
			return false;
	
		}
		
	        return true;
	      			   
		
	}
	
		
	
	private void setButtonsHandlers() {
		
		 
		 Button nuovoOrdineBtn = (Button)  findViewById(R.id.buttonNuovoOrdine);	     
		 nuovoOrdineBtn.setOnClickListener(new OnClickListener() {
	            public void onClick(View view) 
	            {   nuovoOrdine(); 	 }});
		 
		 Button confermaOrdineBtn = (Button)  findViewById(R.id.buttonSalvaOrdine);	     
		 confermaOrdineBtn.setOnClickListener(new OnClickListener() {
	            public void onClick(View view) 
	            {    confermaOrdine(); } });
		 
		

		 Button buttonDeleteOrder = (Button)  findViewById(R.id.buttonDeleteOrder);	     
		 buttonDeleteOrder.setOnClickListener(new OnClickListener() {
	            public void onClick(View view) 
	            {    cancellaOrdine(); } });
		 
	}//fM
	
	private void cancellaOrdine() 
	{					
		_ItemsOrdineList = (ListView) findViewById(R.id.listOrdine);
		_ItemsOrdineList.clearChoices();
		_ItemsOrdineList.setAdapter(null);
		
		//Ordine corrente
		GlobalDatas.CurrentOrder = null;
		GlobalDatas.OrderAdapter = null;
		

		_infoOrdineTxt.setText(""); 
		
	}//fM
	
	private void nuovoOrdine() 
	{					
		//chiama onInputCallComplete definita in interfaccia IInputBoxDelegate
		new InputBoxNewOrder(this).showInputBox(this, "Dati Ordine",  "NuovoOrdine");

		
	}//fM
	
	public void onInputCallComplete(InputData pData, String pToken) {
		
		if(pData == null) 
			return;
		if (pToken == "NuovoOrdine")creaNewOrder(pData);			
					
		
	}//fM


	private void creaNewOrder(InputData pData) {
		
		_ItemsOrdineList = (ListView) findViewById(R.id.listOrdine);
		_ItemsOrdineList.clearChoices();
		_ItemsOrdineList.setTextFilterEnabled(true);
		_ItemsOrdineList.setAdapter(null);
		
		//Ordine corrente
		GlobalDatas.CurrentOrder = null;
		GlobalDatas.CurrentOrder = new myOrdine( pData.TableName,pData.NClienti,  pData.NCoperti  , GlobalDatas.OrderAdapter  );
		
		
		
		 GlobalDatas.OrderAdapter = null;
		 GlobalDatas.OrderAdapter = new ItemOrdineAdapter(this,R.layout.items , GlobalDatas.CurrentOrder.MenuItems );
		 _ItemsOrdineList.setAdapter(GlobalDatas.OrderAdapter); 
		 
		
		 GlobalDatas.CurrentOrder .setAdapter(GlobalDatas.OrderAdapter );
	

		
		 _infoOrdineTxt.setText(""); 		
		 _infoOrdineTxt.setText( "TAVOLO : "+ pData.TableName + ", Clienti : " + String.valueOf( pData.NClienti) );
		
		
		Toast.makeText(getApplicationContext(), "Ordine creato " + pData.TableName + "  " , Toast.LENGTH_SHORT).show();
		
		
	
		// Click sulla listview ordini	
		_ItemsOrdineList.setOnItemClickListener(
				new OnItemClickListener() 	
		{						
		    public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
		    {
		    	TextView txt=	(TextView) view.findViewById(R.id.listItem_Name) ;
		      // When clicked, show a toast with the TextView text  //((TextView) view).getText()
		      Toast.makeText(getApplicationContext(),txt.getText() + "\r\nPosition : "+ position  ,Toast.LENGTH_SHORT).show();
		      
		      InputBoxBool ib= new InputBoxBool(OrderItemsActivity.this);
		      ib.showInputBox("Dati", "Cancellare riga ?", "", OrderItemsActivity.this , "CancellaRiga", position );	          		
				    
		    }
		    }
		);			 
		
		
		
	}//fM
	
	//
	public void onInputBoxBoolCallComplete(Boolean pResponse,Object pTag, String pToken) {
		
		if(pToken == "CancellaRiga")
		{
			if(pResponse == true)
			{
				int pos =Integer.parseInt( pTag.toString());
				
				 Toast.makeText(getApplicationContext(),pResponse.toString() ,Toast.LENGTH_SHORT).show();
				 GlobalDatas.CurrentOrder.MenuItems.remove(pos);
				 GlobalDatas.OrderAdapter.notifyDataSetChanged();
			} 
		}
	}

	

	//onSaveOrderComplete quando il salvataggio ordine completa
	public void onRemoteSaveCallCompleted (HttpEntity pData) {
		
		_progrDialog.cancel();
		String res = resVarie.readJsonString(pData);
		
		if(pData == null) 
			resVarie.Alert2("Dati", "Error saving order", this);
		else
			resVarie.Alert2("Dati", "Saved order \r\n"+  res  , this);
				
					
		
	}//fM

	//quando torna il wcf chiama il metodo onSaveOrderComplete
	private void confermaOrdine() {
		
		if(GlobalDatas.CurrentOrder == null) return;
		if(GlobalDatas.CurrentOrder.MenuItems.size() < 1) return;
		
		_progrDialog = ProgressDialog.show(this, "", "Saving order. Please wait...", true);
		
		//10.0.2.2:8096
		String url = 
			"http://"+ GlobalDatas.NetSettings.HostIp +":"+
			GlobalDatas.NetSettings.Port +
			"/Services/OrdersSvc.svc/SaveOrder";
		
		SaveOrderAsync task1 = new SaveOrderAsync(this, GlobalDatas.CurrentOrder);
	    task1.execute(url);
	    	
	    
		
	}//fM
	

	public void makeTabHostInit()
	{

	    Resources res = getResources(); // Resource object to get Drawables
	    TabHost tabHost = getTabHost();  // The activity TabHost
	    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
	    Intent intent;  // Reusable Intent for each tab
	    
		spec = tabHost.newTabSpec("Ordine").setIndicator("Ordine",
                res.getDrawable(R.drawable.rist2)).setContent(R.id.tab1);
    	tabHost.addTab(spec);
    	
	}
	
	public void makeTabHost()
	{

		if(GlobalDatas.CategorieList == null) return;
		
	    Resources res = getResources(); // Resource object to get Drawables
	    TabHost tabHost = getTabHost();  // The activity TabHost
	    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
	    Intent intent;  // Reusable Intent for each tab
	    ListView litdati = null;
		    
	    //Toast.makeText(getApplicationContext(), "Categorie " + GlobalDatas.CategorieList.size() + ",\r\n piatti "+ GlobalDatas.MenuList.size() , Toast.LENGTH_SHORT).show();
	    	    
	    String catName = "";
	    ArrayList<myMenu> itemsbyCat ;
	    
	    Log.d("In makeTabHost","Cat global menu :"+ GlobalDatas.CategorieList.size());
	    Log.d("In makeTabHost","Items global menu :"+ GlobalDatas.MenuList.size());
	    
	    
	    Drawable[] arrColors = new Drawable[5];
	    arrColors[0] = getResources().getDrawable( R.drawable.cyan1 );
	    arrColors[1] = getResources().getDrawable( R.drawable.green1);
	    arrColors[2] = getResources().getDrawable( R.drawable.yellow1);
	    arrColors[3] = getResources().getDrawable( R.drawable.orange1);
	    arrColors[4] = getResources().getDrawable( R.drawable.red1);
	    int selector=0;
	    
	    
	    for (int i = 0; i < GlobalDatas.CategorieList.size(); ++i) 
        {	        	
	    	//guid = GlobalDatas.CategorieList.get(i).Nome ;
	    	catName = GlobalDatas.CategorieList.get(i).Nome ;
	    	
	    	
	    	itemsbyCat = GlobalDatas.getMenuItens_byCatID(catName);
	    	
	    	Log.d("Diego tab","Items :"+ itemsbyCat.size());
	    	
	    	intent = new Intent(this, ItemsActivity.class );
	    	intent.putExtra("items", itemsbyCat);

	    	
	    	if(selector > 4)selector=0;
	    	
		    spec = tabHost.newTabSpec(catName)
		    .setIndicator(catName.subSequence(0,3),arrColors[selector] ).setContent( intent );
		    		    
		    
		    tabHost.addTab(spec);		    
		    ++selector;
		    
        }   
	    
	  
	    tabHost.setCurrentTab(0);
		
	    
	}//fM




	
	
	
	
}//fC
